<template>
  <div class="common-charts-container">
    <div class="common-charts-item" id="c1"></div>
    <div class="common-charts-item" id="c2"></div>
    <div class="common-charts-item">
      <div id="c3"></div>
      <div id="slider"></div>
    </div>
  </div>
</template>

<script>
import { DataSet } from "@antv/data-set";

export default {
  name: "Lines",
  data() {
    return {};
  },
  mounted() {
    this.renderAll();
  },
  methods: {
    /* renderAll */
    async renderAll() {
      const [c1, c2, c3] = await Promise.all([
        this.renderC2(),
        this.renderC1(),
        this.renderC3()
      ]);
    },
    /* 获取数据 */
    async getData() {
      let res = await this.$https.get("/mock/lines");
      if (res.data.code === 0) {
        return res.data.data;
      }
    },
    async getDataDouble() {
      let res = await this.$https.get("/mock/lines/2");
      if (res.data.code === 0) {
        return res.data.data;
      }
    },
    async getDataThree() {
      let res = await this.$https.get("/mock/lines/3");
      if (res.data.code === 0) {
        return res.data.data;
      }
    },
    /* params: dom,sourceData: Array */
    render(ele = "c1", sourceData = []) {
      let chart = new this.G2.Chart({
        container: ele,
        forceFit: true,
        height: 360,
        padding: "auto"
      });
      // 加载数据
      chart.source(sourceData, {
        Date: {
          type: "timeCat",
          alias: "日期" // 设置属性的别名
        },
        Integer: {
          min: 200
        }
      });
      // 鼠标hover提示
      chart.tooltip({
        crosshairs: {
          type: "line"
        }
      });
      return chart;
    },
    async renderC1() {
      let data = await this.getData();
      // 按照时间排序
      data.sort((a, b) => {
        return new Date(a.Date) - new Date(b.Date);
      });
      // 获取最大值、最小值和平均值
      let tmpList = [];
      data.forEach(val => {
        tmpList.push(val.Integer);
      });
      let MAX = Math.max(...tmpList);
      let MIN = Math.min(...tmpList);
      let AVERAGE = this._lodash.sum(tmpList) / tmpList.length;
      let begin = data[0].Date;
      let end = data[data.length - 1].Date;

      let chart = this.render("c1", data);
      // 线
      chart.line().position("Date*Integer");
      // 点
      chart
        .point()
        .position("Date*Integer")
        .size(4)
        .shape("circle")
        .style({
          stroke: "#fff",
          lineWidth: 1
        })
        .label("Date*Integer", function(Date, Integer) {
          // return Integer + "万"
          return "";
        });
      /*均线值*/
      chart.guide().line({
        top: true,
        start: [begin, AVERAGE],
        end: [end, AVERAGE],
        lineStyle: {
          stroke: "#595959",
          lineWidth: 1,
          lineDash: [3, 3]
        },
        text: {
          position: "start",
          style: {
            fill: "#8c8c8c",
            fontSize: 12,
            fontWeight: 300
          },
          content: `均值线 ${AVERAGE}万`,
          offsetY: -5
        }
      });

      chart.render();
    },
    async renderC2() {
      let data = await this.getDataDouble();
      // 创建数据集
      let ds = new DataSet();
      let dv = ds.createView().source(data);
      dv.transform({
        type: "fold",
        fields: ["y1", "y2"], // 展开字段集
        key: "date",
        value: "integer" // value字段
      });

      let chart = this.render("c2", dv);
      // 多条折线
      chart
        .line()
        .position("Date*integer")
        .shape("smooth")
        .color("date");
      chart
        .point()
        .position("Date*integer")
        .shape("circle")
        .color("date")
        .size(3);
      chart.render();
    },
    /* 创建镜像图 */
    async renderC3() {
      let $this = this;
      let data = await this.getDataThree();

      /*创建数据集*/
      let ds = new DataSet({
        state: {
          start: new Date(data[0].time).getTime(),
          end: new Date(data[data.length - 1].time).getTime()
        }
      });

      let originDv = ds.createView("origin");
      originDv.source(data).transform({
        type: "fold",
        fields: ["rain", "flow"],
        key: "type",
        value: "value",
        retains: ["rain", "flow", "time"]
      });

      let chartDv = ds.createView();
      chartDv
        .source(originDv)
        .transform({
          type: "fold",
          fields: ["rain", "flow"],
          key: "type",
          value: "value",
          retains: ["rain", "flow", "time"]
        })
        .transform({
          type: "filter",
          callback: function callback(obj) {
            var time = new Date(obj.time).getTime(); // !注意：时间格式，建议转换为时间戳进行比较
            return time >= ds.state.start && time <= ds.state.end;
          }
        });

      let chart = new this.G2.Chart({
        container: "c3",
        forceFit: true,
        height: 330,
        padding: "auto",
        animate: true
      });
      chart.source(chartDv, {
        time: {
          type: "time",
          tickCount: 10
        }
      });
      /*设置分面*/
      chart.facet("mirror", {
        fields: ["type"],
        showTitle: false, // 显示标题
        padding: [0, 0, 40, 0],
        eachView: function eachView(view, facet) {
          let colValue = facet.colValue;
          let data = facet.data;

          let color = void 0;
          let alias = void 0;
          if (colValue === "rain") {
            color = "#1890ff";
            alias = "降雨量(mm)";
          } else if (colValue === "flow") {
            color = "#2FC25B";
            alias = "流量(m^3/s)";
          }
          view.source(
            data,
            $this._defineProperty({}, "" + colValue, {
              alias: alias
            })
          );
          view.axis(colValue, {
            title: {
              autoRotate: false,
              offset: -10,
              position: "end",
              textStyle: {
                textAlign: "start"
              }
            }
          });
          view
            .line()
            .position("time*" + colValue)
            .color(color);
        }
      });
      chart.render();

      // 创建 Slider
      chart.interact("slider", {
        container: "slider",
        start: ds.state.start, // 和状态量对应
        end: ds.state.end,
        xAxis: "time",
        yAxis: "value",
        data: originDv,
        backgroundChart: {
          type: "line",
          color: "grey"
        },
        onChange: function onChange(_ref) {
          var startValue = _ref.startValue,
            endValue = _ref.endValue;

          ds.setState("start", startValue);
          ds.setState("end", endValue);
        }
      });
    },
    _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, {
          value: value,
          enumerable: true,
          configurable: true,
          writable: true
        });
      } else {
        obj[key] = value;
      }
      return obj;
    }
  }
};
</script>

<style scoped lang="scss"></style>
